package com.example.designpatterns.model.observer.eventbus;

import com.example.designpatterns.model.observer.demo.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.concurrent.Executors;

/**
 * @author yanyun zhu
 * @version 1.0
 * @date 2022/1/4 11:34
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService; // 依赖注入

    private EventBus eventBus;
    private static final int DEFAULT_EVENTBUS_THREAD_POOL_SIZE = 20;

    public UserController() {
        //eventBus = new EventBus(); // 同步阻塞模式
        eventBus = new AsyncEventBus(Executors.newFixedThreadPool(DEFAULT_EVENTBUS_THREAD_POOL_SIZE)); // 异步非阻塞模式
    }

    public void setRegObservers(List<Object> observers) {
        for (Object observer : observers) {
            eventBus.register(observer);
        }
    }

    public Long register(String telephone, String password) {
        //省略输入参数的校验代码
        //省略userService.register()异常的try-catch代码
        long userId = userService.register(telephone, password);

        eventBus.post(userId);
        return userId;
    }
}

//class RegPromotionObserver {
//    private PromotionService promotionService; // 依赖注入
//
//    @Subscribe
//    public void handleRegSuccess(Long userId) {
//        System.out.println("RegPromotionObserver");
//        promotionService.issueNewUserExperienceCash(userId);
//    }
//}

//class RegNotificationObserver {
//    private NotificationService notificationService;
//
//    @Subscribe
//    public void handleRegSuccess(Long userId) {
//        System.out.println("RegNotificationObserver========");
//        notificationService.sendInboxMessage(userId);
//    }
//}
